//
//  WDHTTPRequesTool.m
//  winterTest
//
//  Created by wwinter on 15/12/21.
//  Copyright © 2015年 winter. All rights reserved.
//

#import "WDHTTPRequesTool.h"

@interface WDHTTPRequesTool ()

/**  */
@property (nonatomic, strong) NSArray *mimeTypes;

@end

@implementation WDHTTPRequesTool

-(NSArray *)mimeTypes
{
    return @[@"image/jpeg", @"audio/amr", @"text/text"];
}

+ (instancetype)shareWDHTTPRequesTool
{
    static id instance = nil;
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        instance = [[[self class] alloc] init];
    });
    return instance;
}

- (instancetype)init
{
    if (self = [super init]) {
        // 设置请求响应格式
        self.responseSerializer = [AFHTTPResponseSerializer serializer];
        self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/json", @"text/html", @"text/javascript", nil];
        
        self.requestSerializer.timeoutInterval = 10.0;
        
        // 加上这行代码，https ssl 验证。
        self.securityPolicy = [self customSecurityPolicy];
    }
    return self;
}

- (AFSecurityPolicy*)customSecurityPolicy
{
    // /先导入证书
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"hgcang" ofType:@"cer"];//证书的路径
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    
    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = NO;
    
    securityPolicy.pinnedCertificates = @[certData];
    
    return securityPolicy;
}

- (void)sendRequestWithGETURL:(NSString *)url
                   completion:(void(^)(NetState netState, id callbackData))completion
{
    NSString *urlUTF = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [self GET:urlUTF parameters:nil
      success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        if (completion) {
            completion(net_Connect_SUCCES, responseObject);
        }
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        if (completion) {
            completion(net_Connect_Failed, error);
            NSLog(@"请求失败 url = %@",url);
        }
    }];
}

- (void)sendRequestWithPostURL:(id)url
                          body:(NSDictionary *)bodyDic
                    completion:(void (^)(NetState netState, id callbackData))completion
{
    NSString *urlUTF = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [self POST:urlUTF parameters:bodyDic
       success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        if (completion) {
            completion(net_Connect_SUCCES, responseObject);
        }
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        if (completion) {
            completion(net_Connect_Failed, error);
            NSLog(@"请求失败 url = %@",url);
        }
    }];
}

- (void)uploadDataWith:(NSData *)data
                   url:(NSString *)url
              fileName:(NSString *)fileName
              mimeType:(MimeType)mimeType
                params:(NSDictionary *)params
              progress:(void (^)(CGFloat progressValue))progress
            completion:(void (^)(NetState netState, id callbackData))completion
{
    NSString *mimeTypeStr = self.mimeTypes[mimeType];
    
    AFHTTPRequestOperation *operation = [self POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:data name:@"user" fileName:fileName mimeType:mimeTypeStr];
    } success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        if (completion) {
            completion(net_Connect_SUCCES, responseObject);
        }
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        if (completion) {
            completion(net_Connect_Failed, error);
            NSLog(@"上传失败 url = %@",url);
        }
    }];
    
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        CGFloat progressValue = (float)totalBytesWritten/(float)totalBytesExpectedToWrite;
        if (progress) {
            progress(progressValue);
        }
    }];
    [operation start];
}
@end
